import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { User } from 'src/system/user/entities/user.entity';
import { UserService } from 'src/system/user/user.service';
import { ConfigService } from '@nestjs/config';
import { RedisService } from 'src/db/redis-cache.service';
import { HttpService } from 'src/http/http.service';
import { Request } from 'express';
import { CreateAuthDto } from './dto/create-auth.dto';
import { v4 as uuidv4 } from 'uuid';
import { ExtractJwt } from 'passport-jwt';
var parser = require('ua-parser-js');
@Injectable()
export class AuthService {
  constructor(
    private jwtService: JwtService,
    private userService: UserService,
    private configService: ConfigService,
    private redisService: RedisService,
    private httpService: HttpService,
  ) {}

  // 生成token
  async createToken(user: Partial<User>) {
    return this.jwtService.sign(user);
  }

  //登录
  async login(user: CreateAuthDto, request: Request) {
    let exitUser = request.user as User;
    if (exitUser.status != '0' && exitUser.id != 1) {
      throw new HttpException('该用户已被停用！', HttpStatus.BAD_REQUEST);
    }
    const ua = parser(request.headers['user-agent']);
    const ipAddress = await this.httpService.getIpAddress(request.ip);
    const token = await this.createToken({
      id: exitUser?.id,
      username: user.username,
    });
    await this.redisService.set(
      `login_token:${token}`,
      {
        token,
        ua,
        ipAddress,
        ip: request.ip,
        user: exitUser,
        loginTime: new Date().getTime(),
        token_id: uuidv4(),
      },
      this.configService.get('REDIS_TIMEOUT'),
    );
    return { token, ua, ip: request.ip };
  }

  // 查询用户信息
  async getUser(user) {
    return await this.userService.findOne(user.id);
  }

  // 登出
  async logout(request: Request) {
    const token = ExtractJwt.fromAuthHeaderAsBearerToken()(request);
    await this.redisService.del(`login_token:${token}`);
    return {
      message: '用户已登出',
    };
  }

  /**
   * 缓存列表
   * @returns
   */

  async getRedisKey() {
    return await this.redisService.getAllKey();
  }
}
